import React, { Fragment, useState } from 'react';
import { Card, Table, Popover, Tooltip, Button, Input, Icon, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { AUDIT, NEWAUTH, GRADE, STATUS } from '@/pages/Organization/OrgFlow/constant';
import { router, withRouter } from 'umi';
import IconFont from '@/components/IconFont';
import { useRequest } from '@/hooks';
import { fetchFunctionList, fetchManageList } from '@/pages/Setting/Privilege/services';
// import dataSource from './mock';
import { GroupLabel } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { removeEmptyChildren, tree2array } from '@/utils/tree';
import { gotoWorkFlowDetail } from '@/pages/WorkFlow/utils';
import cloneDeep from 'lodash/cloneDeep';
import debounce from 'lodash/debounce';
import { HighlightText } from '@/molecules';
import { GuideByServerFlag } from '@/components';
import PopSaveCont from '@/pages/Setting/Privilege/components/PopSaveCont';
import authHelpr from '@/utils/auth/helper';
import cn from 'classnames';
import styles from '../index.less';

const { Search } = Input;
const { checkCode } = authHelpr;

// 处理从url取下来的参数出现字符串，所以转成纯数字
const arrInStringToNumber = array => {
    if (array && Array.isArray(array)) {
        return array.map(Number);
    }
    if (array && typeof array === 'string') {
        return [Number(array)];
    }
    return undefined;
};

// 俩数组合并并去重
const arrayNewSet = (arr1, arr2) => Array.from(new Set(arr1.concat(arr2)));
const List = ({ location }) => {
    const { query = {} } = location; // url参数

    // 判断url上面没值的情况,使其高亮准确
    const urlValue = React.useMemo(() => Object.values(query), [query]);
    const isUrlValue = () => {
        if (urlValue.length === 0) {
            return false;
        }
        return urlValue.some(item => item !== undefined && item.length > 0);
    };
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    // const [selectedRows, setSelectedRows] = useState([]);

    const [expandAllRows, setExpandAllRows] = useState([]); // 展开项控制
    // 0-收起 1-展开
    const [slider, setSlider] = useState(1);
    // 获取功能权限数据
    const { loading, data } = useRequest(
        () => {
            const params = {
                keyword: query.keyword || undefined,
                types: arrInStringToNumber(query.type) || undefined,
                auditStatuses: arrInStringToNumber(query.auditStatus) || undefined,
                functionGrades: arrInStringToNumber(query.functionGrade) || undefined,
                isEnables: arrInStringToNumber(query.isEnable) || undefined
            };

            return fetchFunctionList(params);
        },
        {
            refreshDeps: [query],
            onSuccess: e => {
                const { code } = e;
                if (code === 10000) {
                    const allIds = tree2array(data?.data).map(item => item.resourceCode);
                    // 思路 selectedRowKeys 选中的ids  当前搜索条件后的所有ids allIds
                    const list = allIds.filter(items => {
                        if (selectedRowKeys.includes(items)) {
                            return items;
                        }
                        return '';
                    });
                    setSelectedRowKeys(list);

                    // 如果url搜索，展开全部/如果没有展开一级
                    if (isUrlValue()) {
                        setExpandAllRows(allIds);
                    } else {
                        setExpandAllRows(data?.data.map(item => item.resourceCode));
                    }
                }
            }
        }
    );
    // 获取授权模板的所有模板
    const { data: manageList } = useRequest(fetchManageList);
    const tableData = React.useMemo(() => removeEmptyChildren(data?.data), [data]);
    // 编辑
    const handleEdit = arr => {
        if (arr && arr.length > 0) {
            // 由于如果存浏览器url上，批量操作可能数据非常长，为了避免丢失，这边做了两块处理，批量操作的话，读取缓存
            // 普通查看详情及修改读取url
            localStorage.setItem('authEditId', JSON.stringify(arr));
            if (arr.length === 1) {
                history.push({
                    pathname: '/setting/privilege/functionManagement/edit',
                    query: {
                        authEditId: JSON.stringify(arr)
                    }
                });
            } else if (arr.length > 1) {
                history.push({
                    pathname: '/setting/privilege/functionManagement/batchEdit',
                    query: {
                        authEditId: JSON.stringify(arr)
                    }
                });
            }
        }
    };
    // const tableDataArr = React.useMemo(() => tree2array(data?.data), [data]);

    // 批量操作
    const handleEditBatch = () => {
        // const rows = tableDataArr.filter(item => selectedRowKeys.some(i => item.resourceCode === i));
        handleEdit(selectedRowKeys);
    };
    // 选中行
    const handleTableSelect = (record, selected) => {
        // 选中子集
        // 获取选中的内容
        // 规则选中父级勾选当前底下子集 取消父级取消当前底下的子集--交互聚强-产品TiMi已知
        if (selected) {
            const ids = tree2array([cloneDeep(record)]).map(item => {
                if (item.auditStatus !== 1) {
                    return item.resourceCode;
                }
                return '';
            });
            setSelectedRowKeys(arrayNewSet(selectedRowKeys, ids));
        } else {
            const ids = tree2array([cloneDeep(record)]).map(item => {
                if (item.auditStatus !== 1) {
                    return item.resourceCode;
                }
                return '';
            });
            const list = selectedRowKeys.filter(items => {
                if (!ids.includes(items)) {
                    return items;
                }
                return '';
            });
            setSelectedRowKeys(list);
        }
    };
    // 表格里的展开功能
    const rowSelection = {
        onChange: selectedRowKeysTemp => {
            setSelectedRowKeys(selectedRowKeysTemp);
            // setSelectedRows(selectedRowsTemp);
        },
        onSelect: handleTableSelect,
        getCheckboxProps: record => ({
            disabled: record.auditStatus === 1
        }),
        selectedRowKeys
    };

    // 查看审批详情
    const handleToDetail = auditCode => {
        history.push(gotoWorkFlowDetail(auditCode));
    };

    const renderOperation = (resourceCode, auditStatus) =>
        checkCode('system:authorization:resource:edit') ? (
            <Tooltip title="编辑">
                <i
                    className={cn('iconfont iconlistfunction_edit_icon_default', styles.icon)}
                    onClick={() => handleEdit([resourceCode])}
                    disabled={auditStatus === 1 || !checkCode('system:authorization:resource:edit')}
                />
            </Tooltip>
        ) : null;

    const renderNameZh = (text, record) => (
        <Fragment>
            {record.remarkZh ? (
                <Popover content={<div>功能简介: {record.remarkZh}</div>} trigger="hover">
                    <span>
                        <HighlightText keywords={query?.keyword ? [query.keyword] : []}>{text}</HighlightText>
                    </span>
                </Popover>
            ) : (
                <HighlightText keywords={query?.keyword ? [query.keyword] : []}>{text}</HighlightText>
            )}

            {record.draft && Object.values(record.draft).length > 0 ? (
                <Popover content={<PopSaveCont draft={record.draft} />} trigger="hover">
                    <Icon type="info-circle" style={{ marginLeft: 4 }} />
                </Popover>
            ) : null}
        </Fragment>
    );
    const columns = [
        {
            title: '功能',
            key: 'nameZh',
            dataIndex: 'nameZh',
            render: (text, record) =>
                checkCode('system:authorization:resource:detail') ? (
                    <a
                        className={styles.aClick}
                        onClick={() => {
                            localStorage.setItem('authEditId', JSON.stringify([record.resourceCode]));
                            history.push({
                                pathname: '/setting/privilege/functionManagement/detail',
                                query: {
                                    authEditId: JSON.stringify([record.resourceCode])
                                }
                            });
                        }}
                    >
                        {renderNameZh(text, record)}
                    </a>
                ) : (
                    <span>{renderNameZh(text, record)}</span>
                )
        },
        {
            title: '类型',
            key: 'type',
            dataIndex: 'type',
            filteredValue: arrInStringToNumber(query.type),
            filters: [
                { text: NEWAUTH['0'], value: 0 },
                { text: NEWAUTH['1'], value: 1 },
                { text: NEWAUTH['2'], value: 2 },
                { text: NEWAUTH['3'], value: 3 }
            ],
            render: text => NEWAUTH[text] || ''
        },
        {
            title: '审批',
            key: 'auditStatus',
            dataIndex: 'auditStatus',
            filteredValue: arrInStringToNumber(query.auditStatus),
            filters: [
                { text: AUDIT['1'], value: 1 },
                { text: AUDIT['2'], value: 2 }
            ],
            render: (value, record) => {
                const { auditCode } = record;
                if (value) {
                    if (auditCode) {
                        return (
                            <a
                                onClick={() => {
                                    handleToDetail(auditCode);
                                }}
                            >
                                {AUDIT[value]}
                            </a>
                        );
                    }
                    return <span>{AUDIT[value]}</span>;
                }
                return '-';
            }
        },
        {
            title: '等级',
            key: 'functionGrade',
            dataIndex: 'functionGrade',
            filteredValue: arrInStringToNumber(query.functionGrade),
            filters: [
                { text: GRADE['1'], value: 1 },
                { text: GRADE['2'], value: 2 },
                { text: GRADE['3'], value: 3 }
            ],
            render: text => {
                if (text === 3) {
                    return <span style={{ color: '#000' }}>{GRADE[text]}</span>;
                }
                if (text === 1) {
                    return <span style={{ color: 'rgba(0, 0, 0, 0.35)' }}>{GRADE[text]}</span>;
                }
                return GRADE[text] || '';
            }
        },
        {
            title: '授权',
            key: 'roleCount',
            dataIndex: 'roleCount',
            render: (_, record) => (
                <div style={{ display: 'inline-block' }}>
                    <GroupLabel
                        title="授权模板"
                        data={manageList?.data || []}
                        value={record.roleCodes || []}
                        renderTag={value => <span style={{ cursor: 'default' }}>{value.length}</span>}
                    />
                </div>
            )
        },
        {
            title: '状态',
            key: 'isEnable',
            dataIndex: 'isEnable',
            filteredValue: arrInStringToNumber(query.isEnable),
            filters: [
                { text: STATUS[0], value: 1 },
                { text: STATUS[1], value: 0 }
            ],
            render: (_, record) => (record.isEnable ? '已开启' : '已禁用')
        },
        {
            title: '操作',
            key: 'operation',
            dataIndex: 'operation',
            width: 130,
            render: (text, record) => {
                const { auditStatus, auditCode, resourceCode } = record;
                return (
                    <Fragment>
                        {auditStatus !== 1 ? renderOperation(resourceCode, auditStatus) : null}
                        {auditCode ? (
                            <Tooltip title="查看审批详情">
                                <i
                                    className={cn('iconfont iconlistfunction_viewinterview_icon_default', styles.icon)}
                                    onClick={() => handleToDetail(auditCode)}
                                />
                            </Tooltip>
                        ) : null}
                    </Fragment>
                );
            }
        }
    ];

    const handleTableChange = (_, filters) => {
        history.replace({
            query: {
                ...query,
                ...filters
            }
        });
    };

    const allRowId = React.useMemo(() => tree2array(data?.data).map(item => item.resourceCode), [data]);
    const [expandLoading, setExpandLoading] = useState(false);
    // 缩放展开
    const handleSlider = debounce(
        () => {
            if (slider === 1) {
                setExpandLoading(true);
                setTimeout(() => {
                    setSlider(0);
                    setExpandAllRows(allRowId);
                    setExpandLoading(false);
                });
            } else {
                setExpandLoading(true);
                setTimeout(() => {
                    setSlider(1);
                    setExpandAllRows([]);
                    setExpandLoading(false);
                });
            }
        },
        300,
        {
            leading: true,
            trailing: false
        }
    );

    return (
        <PageHeaderWrapper>
            <GuideByServerFlag serverStorageKey="guideFunctionManagement">
                <Card
                    title={
                        <GuideByServerFlag.Step
                            placement="rightTop"
                            title="【功能管理】板块"
                            content="可查看系统中各个功能及权限配置"
                        >
                            <span>功能管理</span>
                        </GuideByServerFlag.Step>
                    }
                >
                    <Spin spinning={expandLoading}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
                            <div>
                                <Search
                                    placeholder="搜索功能名称"
                                    allowClear
                                    defaultValue={query.keyword}
                                    onSearch={value => {
                                        history.replace({
                                            query: {
                                                ...query,
                                                keyword: value || undefined
                                            }
                                        });
                                    }}
                                    style={{ width: 240 }}
                                />
                            </div>
                            <div>
                                {checkCode('system:authorization:resource:batch_edit') ? (
                                    <GuideByServerFlag.Step
                                        placement="left"
                                        content={
                                            <>
                                                选择多个功能，可批量修改权限
                                                <br />
                                                可一次提交多个功能修改的申请
                                            </>
                                        }
                                    >
                                        <Button
                                            type="primary"
                                            onClick={handleEditBatch}
                                            disabled={selectedRowKeys.length === 0}
                                        >
                                            批量操作
                                        </Button>
                                    </GuideByServerFlag.Step>
                                ) : null}

                                <Tooltip title={slider === 0 ? '收起子功能' : '展开子功能'}>
                                    <a
                                        onClick={() => {
                                            handleSlider();
                                        }}
                                        className={styles.aClick}
                                        style={{
                                            width: 30,
                                            display: 'inline-block',
                                            textAlign: 'center',
                                            marginLeft: 12
                                        }}
                                    >
                                        {slider === 0 ? (
                                            <IconFont icon="iconshouqisuoyouzigongneng" style={{ fontSize: 20 }} />
                                        ) : (
                                            <IconFont icon="iconzhankaisuoyouzigongneng" style={{ fontSize: 20 }} />
                                        )}
                                    </a>
                                </Tooltip>
                            </div>
                        </div>
                        <Table
                            // defaultExpandAllRows
                            columns={columns}
                            loading={loading}
                            rowSelection={rowSelection}
                            dataSource={tableData}
                            expandedRowKeys={expandAllRows}
                            onExpandedRowsChange={e => {
                                setExpandAllRows(e);
                            }}
                            rowClassName={record => {
                                if (isUrlValue()) {
                                    return record?.isMatch ? styles.hightRow : null;
                                }
                                return null;
                            }}
                            onChange={handleTableChange}
                            rowKey="resourceCode"
                            pagination={false}
                            expandIcon={({ expanded, onExpand, record }) => {
                                const { children } = record;
                                if (!children) {
                                    return <span style={{ width: 14, height: 14 }} />;
                                }
                                return expanded ? (
                                    <Icon
                                        type="caret-down"
                                        style={{ marginRight: 5 }}
                                        onClick={e => onExpand(record, e)}
                                    />
                                ) : (
                                    <Icon
                                        type="caret-right"
                                        style={{ marginRight: 5 }}
                                        onClick={e => onExpand(record, e)}
                                    />
                                );
                            }}
                            // onExpandedRowsChange={handleExpandedRowsChange}
                        />
                    </Spin>
                </Card>
            </GuideByServerFlag>
        </PageHeaderWrapper>
    );
};
export default withRouter(List);
